package com.mvc.dao.impl;

import com.mvc.dao.DogDao;
import com.mvc.dao.TypeDao;
import com.mvc.entity.Dog;
import com.mvc.entity.Type;

import java.util.List;

/**
 * @author wzm
 * @create 2023-04-12 14:17
 */
//DogDao功能的实现类
public class DogDaoImpl  extends BaseDao implements DogDao {
    //要用到TypeDao的方法
    TypeDao typeDao = new TypeDaoImpl();

    //实现增删改查的方法需要调用BaseDao中的操作

    @Override
    public int insert(Dog dog) {
        String sql = "insert into dog values(?,?,?,?,?)";
        //增加的参数从参数对象中获取 由调用者传入
        return update(sql, null,dog.getName(),dog.getAge(),dog.getSex(),dog.getType().getTypeid());
    }

    @Override
    public int delete(Dog dog) {
        String sql = "delete from dog where id = ?";
        return update(sql,dog.getId());
    }

    @Override
    public int update(Dog dog) {
        String sql = "update dog set name = ?,age = ?,sex = ?,typeid = ? where id = ?";
        return update(sql,dog.getName(),dog.getAge(),dog.getSex(),dog.getType().getTypeid(),dog.getId());
    }

    @Override
    public Dog selectById(Dog dog) {
        String sql = "select * from dog where id = ?";
        Dog dog1 = selectForOne(Dog.class, sql, dog.getId());
        //差type 通过当前dog1的typeid查询type
        Type type = typeDao.getTypeById(new Type(dog1.getTypeId(), null));
        dog1.setType(type);
        return dog1;
    }

    @Override
    public List<Dog> selectByList() {
        //方式一 先查询到外建id 然后通过外建id去重新查询
       /* String sql = "select * from dog";
        //涉及多表数据 方案一 多步查询
        List<Dog> dogs = selectForList(Dog.class, sql);


        //根据查询的typeid 去分步查询type的具体内容
        for (int i = 0; i < dogs.size();i++){

            //获取每一条dog的id
            Integer typeId = dogs.get(i).getTypeId();

            //根据id查询type 调用TypeDaoImpl的方法
            Type type = typeDao.getTypeById(new Type(typeId, null));

            //将type赋值给每一条dog
            dogs.get(i).setType(type);

        }

        return dogs;*/

        //方式二 自定义结果集处理器
        String sql = "select d.*,t.typename\n" +
                "from dog d\n" +
                "left join type t\n" +
                "on d.typeid = t.typeid\n";
        List<Dog> list = selectForListByCurs(Dog.class, sql);

        return  list;
    }
}
